package com.rightsidetech.http.controller.userApp.trade;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gexin.fastjson.JSONArray;
import com.gexin.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rightsidetech.activity.dto.request.ActOrderNumReq;
import com.rightsidetech.activity.dto.response.store.app.MtActivityOrderResp;
import com.rightsidetech.activity.entity.*;
import com.rightsidetech.activity.service.ActCouponUserService;
import com.rightsidetech.activity.service.ActGiftService;
import com.rightsidetech.activity.service.MtActivityAppService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.config.RedisKeys;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.EnumPayMode;
import com.rightsidetech.commom.enums.StoreActivityEnum;
import com.rightsidetech.commom.enums.SystemParamsEnum;
import com.rightsidetech.commom.push.EnumMsgType;
import com.rightsidetech.commom.utils.*;
import com.rightsidetech.commom.utils.gps.GPSUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.http.config.WechatConfig;
import com.rightsidetech.http.mq.ProducerMsg;
import com.rightsidetech.http.task.MassageTask;
import com.rightsidetech.http.wechatutil.MsgTemplatesEnum;
import com.rightsidetech.http.wechatutil.WechatUtil;
import com.rightsidetech.mall.dto.response.CommodityOrderDetailResp;
import com.rightsidetech.mall.entity.*;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.mall.service.MallGiftCommodityService;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralDetialReq;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralReq;
import com.rightsidetech.system.dtos.response.store.SysStoreOrderDetailResp;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.entity.SysLevelRule;
import com.rightsidetech.system.entity.SysSystemParam;
import com.rightsidetech.system.entity.store.SysStoreAccountInfo;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.*;
import com.rightsidetech.trade.dtos.request.*;
import com.rightsidetech.trade.dtos.response.*;
import com.rightsidetech.trade.entity.*;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import com.rightsidetech.trade.service.TdCouponUseService;
import com.rightsidetech.user.dtos.response.LoginInfoResp;
import com.rightsidetech.user.dtos.response.UserAddressResp;
import com.rightsidetech.user.entity.UsUserAccountInfo;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userApp/trade")
@ShenyuSpringMvcClient(path = "/userApp/trade/**")
@Api(tags = "用户订单相关")
@Slf4j
public class TdCommodityUserAppController extends BaseController {


    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private WechatConfig wechatConfig;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ProducerMsg producerMsg;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SystemParamService systemParamService;
    @Resource
    private ActGiftService actGiftService;
    @Resource
    private MallGiftCommodityService mallGiftCommodityService;
    @Resource
    private TdCouponUseService tdCouponUseService;
    @Resource
    private ActCouponUserService actCouponUserService;
    @Autowired
    private MassageTask massageTask;
    @Resource
    private SysAgentInfoService sysAgentInfoService;
    @Resource
    private SysStoreStorkService sysStoreStorkService;
    @Resource
    private MtActivityAppService mtActivityAppService;
    @Resource
    private LevelRuleService levelRuleService;
    @Resource
    private SysStoreIntegralService sysStoreIntegralService;
    @Resource
    private SysRuleCommodityIntegralService sysRuleCommodityIntegralService;

    private final ReentrantLock lock = new ReentrantLock();


    @Log
    @Token
    @ApiOperation("用户统一下单")
    @PostMapping("/placeOrder")
    public ResponseData placeOrder(@RequestBody TdCommodityUserAppOrderRequest req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        if (StringUtil.isNullorEmpty(req.getList()) || req.getList().isEmpty()) {
            return ResponseData.fail(CodeIdEnum.NonCommodity);
        }
        for (TdCommodityUserAppOrderDetailRequest req2 : req.getList()) {
            ConstraintViolation validate2 = BeanValidator.validate(req2);
            if (validate != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate2.getMessage());
            }
        }
        List<TdCommodityOrderDetails> list = new ArrayList<>();

        List<TdCommodityOrderDetails> list2 = new ArrayList<>();

        List<TdCommodityUserGiftRecord> list3 = new ArrayList<>();

        //查询门店信息
        SysStoreOrderDetailResp sysStoreOrderDetailResp = sysStoreInfoService.findOrderDetailByStoreId(req.getStoreId());
        if (StringUtil.isNullorEmpty(sysStoreOrderDetailResp)) {
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        if (sysStoreOrderDetailResp.getStatus() == -1){
            return ResponseData.fail(CodeIdEnum.STOREClOSEDINFO);
        }
        if (sysStoreOrderDetailResp.getStatus() != 1){
            return ResponseData.fail(CodeIdEnum.NonStoreInfo.getValue(),"该门店已关闭,订单无法完成,您可手动取消");
        }
        //判断代理商
        SysAgentInfo sysAgentInfo = sysAgentInfoService.selectSysAgentInfo(sysStoreOrderDetailResp.getAgentId());
        if (ObjectUtils.isEmpty(sysAgentInfo)) {
            return ResponseData.fail(CodeIdEnum.NOAGENT);
        }
        if (sysAgentInfo.getStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.AGENTSTOP);
        }

        SysStoreAccountInfo sysStoreAccountInfo = sysStoreInfoService.findStoreAccountInfoByStoreId(req.getStoreId());

        if (StringUtil.isNullorEmpty(sysStoreAccountInfo)) {
            return ResponseData.fail(CodeIdEnum.NOSTOREMSG);
        }
        Long userInfoId = Long.parseLong(getAttribute());

        UserAddressResp userAddressResp2 = null;
        //判断上门服务是否超出范围
        if (req.getOrderType() == 0) {
            if (StringUtil.isNullorEmpty(req.getAddressId())) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "地址不能为空");
            }
            userAddressResp2 = userInfoService.findAddressByUserInfoId(req.getAddressId(), userInfoId);
            if (StringUtils.isEmpty(userAddressResp2)) {
                return ResponseData.fail(CodeIdEnum.NOADDRESS);
            }
            //判断上门的经纬度和门店的经纬度距离
            double lat1 = sysStoreOrderDetailResp.getLatitude().doubleValue();
            double lng1 = sysStoreOrderDetailResp.getLongitude().doubleValue();

            double lat2 = userAddressResp2.getLatitude().doubleValue();
            double lng2 = userAddressResp2.getLongitude().doubleValue();

            double distance = GPSUtil.getDistance(lat1, lng1, lat2, lng2);

            SysSystemParam param2 = systemParamService.findByParamKey(SystemParamsEnum.MAX_SCOPE.getValue());
            if (!ObjectUtils.isEmpty(param2)) {
                String paramValue = param2.getParamValue();
                BigDecimal maxScope = new BigDecimal(paramValue);
                maxScope = maxScope.multiply(new BigDecimal("1000"));
                if (distance > maxScope.doubleValue()) {
                    return ResponseData.fail(CodeIdEnum.OUTSCOPE);
                }
            }
        }

        //邮寄地址标识
        boolean b5 = false;
        //判断商品是否上架
        for (TdCommodityUserAppOrderDetailRequest order1 : req.getList()) {
            CommodityOrderDetailResp mallDetail = mallCommodityService.findOrderDetailByCommodityId(order1.getCommodityId());
            if (StringUtil.isNullorEmpty(mallDetail)) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }
            if (mallDetail.getCommodityStatus() == -2){
                return ResponseData.fail(CodeIdEnum.DOWNPRODUCT);
            }
            if (mallDetail.getCommodityStatus() != 3) {
                return ResponseData.fail(CodeIdEnum.NOCOMMODITYSTATUS);
            }
            boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreOrderDetailResp.getAgentId(), order1.getCommodityId());
            if (!b6) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }
            //换购商品数量
            int zpCommodityNum = 0;
            //判断赠品
            if (!StringUtil.isNullorEmpty(order1.getList()) && !order1.getList().isEmpty()) {
                for (TdCommodityUserAppOrderDetailZPRequest zpOrder : order1.getList()) {

                    //判断赠品的状态
                    MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(zpOrder.getCommodityId());

                    if (StringUtil.isNullorEmpty(mallGiftCommodity)) {
                        return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                    }

                    boolean b4 = actGiftService.checkGift(mallDetail.getTypeId(), zpOrder.getCommodityId(), req.getStoreId());
                    if (!b4) {
                        return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                    }

                    zpOrder.setIsExpress(false);
                    //判断是否是邮寄的赠品
                    if (mallGiftCommodity.getGiftType() == 0) {
                        b5 = true;
                        zpOrder.setIsExpress(true);
                    }

                    zpCommodityNum = zpCommodityNum + zpOrder.getCommodityNum();
                }
            }
            //判断换购/赠品数量 > 商品数量
            if (zpCommodityNum > order1.getCommodityNum()) {
                return ResponseData.fail(CodeIdEnum.OUTOFZPCommodityNum);
            }
        }
        //收货或提货地址不能为空
        UserAddressResp userAddressResp = null;
        if (req.getOrderType() == 0){
            if (StringUtil.isNullorEmpty(req.getAddressId())) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "地址不能为空");
            }
            userAddressResp = userInfoService.findAddressByUserInfoId(req.getAddressId(), userInfoId);
            if (StringUtils.isEmpty(userAddressResp)) {
                return ResponseData.fail(CodeIdEnum.NOADDRESS);
            }
        } else {
            if (StringUtil.isNullorEmpty(req.getUsPhoneNo())) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "手机号不能为空");
            }
        }

        //判断邮寄地址
        UserAddressResp mailAddressResp = null;
        if (b5) {
            if (StringUtil.isNullorEmpty(req.getMailId())) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "邮寄地址不能为空");
            }
            mailAddressResp = userInfoService.findAddressByUserInfoId(req.getMailId(), userInfoId);
            if (StringUtils.isEmpty(mailAddressResp)) {
                return ResponseData.fail(CodeIdEnum.NOADDRESS);
            }
        }



        //校验消息重复消费
        try {
            boolean redisLock = redisUtils.getRedisRequestId(RedisKeys.ORDER_CONSUMER_REQUESTID + req.getRequestId(), req.getRequestId(), 10, 1000L);
            if (redisLock) {
                log.info("消费成功, key={}", RedisKeys.ORDER_CONSUMER_REQUESTID + req.getRequestId());
            } else {
                log.info("消费失败, 重复消费, key={}", RedisKeys.ORDER_CONSUMER_REQUESTID + req.getRequestId());
                return ResponseData.fail(CodeIdEnum.RepeatSubmit);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //统计商品价格
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal discountAmount = new BigDecimal("0");

        //统计换购商品列表和数量
        List<ActOrderNumReq> actOrderNumReqList = new ArrayList<>();

        //1.创建订单
        TdCommodityUserOrder tdCommodityUserOrder = new TdCommodityUserOrder();
        //年月日时分秒 + 随机数3位
        String orderNo = DateUtil.getDate(new Date(), "yyyyMMddHHmmss") + (int) (Math.random() * 900 + 100);
        tdCommodityUserOrder.setOrderNo(orderNo);
        tdCommodityUserOrder.setUserInfoId(userInfoId);

        if (req.getOrderType() == 0) {
            tdCommodityUserOrder.setUsName(userAddressResp.getUserName());
            tdCommodityUserOrder.setUsPhoneNo(userAddressResp.getUserPhone());
            tdCommodityUserOrder.setUsAddress(userAddressResp.getAddress()
                    + (StringUtils.isEmpty(userAddressResp.getDoorplate()) ? "" : userAddressResp.getDoorplate()));
            tdCommodityUserOrder.setLongitude(userAddressResp.getLongitude());
            tdCommodityUserOrder.setLatitude(userAddressResp.getLatitude());
        } else {
            tdCommodityUserOrder.setUsName(req.getUsName());
            tdCommodityUserOrder.setUsPhoneNo(req.getUsPhoneNo());
            tdCommodityUserOrder.setUsAddress(sysStoreOrderDetailResp.getAddress());
            tdCommodityUserOrder.setLongitude(sysStoreOrderDetailResp.getLongitude());
            tdCommodityUserOrder.setLatitude(sysStoreOrderDetailResp.getLatitude());
        }

        tdCommodityUserOrder.setStoreId(req.getStoreId());
        tdCommodityUserOrder.setStoreName(sysStoreOrderDetailResp.getStoreName());
        tdCommodityUserOrder.setCreatedAt(new Date());
        tdCommodityUserOrder.setOrderStatus((byte) 0);
        tdCommodityUserOrder.setRemarks(req.getRemarks());
        tdCommodityUserOrder.setOrderType(req.getOrderType());
        tdCommodityUserOrder.setAgentId(sysStoreOrderDetailResp.getAgentId());
        tdCommodityUserOrder.setAgentName(sysStoreOrderDetailResp.getAgentName());
        tdCommodityUserOrder.setAreaId(sysStoreOrderDetailResp.getAreaId());
        tdCommodityUserOrder.setAreaName(sysStoreOrderDetailResp.getAreaName());
        tdCommodityUserOrder.setSource((byte) 0);
//        if(b5){
//            tdCommodityUserOrder.setGiftAddress(userAddressResp.getAddress() + userAddressResp.getDoorplate());
//        }


        //2.查询用户的商品信息
        long count = 0;
        for (TdCommodityUserAppOrderDetailRequest appDetail : req.getList()) {
            TdCommodityOrderDetails orderDetails = new TdCommodityOrderDetails();
            orderDetails.setOrderNo(tdCommodityUserOrder.getOrderNo());
            CommodityOrderDetailResp mallDetail = mallCommodityService.findOrderDetailByCommodityId(appDetail.getCommodityId());
            MallCommoditySpecs mallCommoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(appDetail.getCommodityId(), appDetail.getCommodityBarCode());

            orderDetails.setCommodityId(mallDetail.getCommodityId());
            orderDetails.setCommodityName(mallDetail.getCommodityName());
            if (!StringUtil.isNullorEmpty(appDetail.getCommodityBarCode()) && !StringUtil.isNullorEmpty(mallCommoditySpecs)) {
                if (appDetail.getBuyType() == 0) {
                    orderDetails.setCommodityPrice(mallCommoditySpecs.getPrice());
                } else {
                    orderDetails.setCommodityPrice(mallCommoditySpecs.getInNewPrice());
                }
                orderDetails.setPicture(mallCommoditySpecs.getPicture());
            } else {
                if (appDetail.getBuyType() == 0) {
                    orderDetails.setCommodityPrice(mallDetail.getPrice());
                } else {
                    orderDetails.setCommodityPrice(mallDetail.getInNewPrice());
                }
                orderDetails.setPicture(mallDetail.getCover());
            }

            orderDetails.setCommodityNum(appDetail.getCommodityNum());
            orderDetails.setCommodityBarCode(appDetail.getCommodityBarCode());
            orderDetails.setCommoditySpecs(appDetail.getCommoditySpecs());
            orderDetails.setPrice(mallDetail.getPrice());
            orderDetails.setUnderlinedPrice(mallDetail.getUnderlinedPrice());
            orderDetails.setTypeId(mallDetail.getTypeId());
            orderDetails.setTypeName(mallDetail.getTypeName());
            orderDetails.setBrandId(mallDetail.getBrandId());
            orderDetails.setBrandName(mallDetail.getBrandName());
            orderDetails.setCommodityTag((byte) 0);
            orderDetails.setBuyType(appDetail.getBuyType());
            orderDetails.setCode(mallDetail.getCode());
            orderDetails.setOrderStatus((byte) 0);
            orderDetails.setCreatedAt(new Date());
            orderDetails.setParentId(count);

            list.add(orderDetails);

            totalAmount = totalAmount.add(orderDetails.getCommodityPrice().multiply(new BigDecimal(orderDetails.getCommodityNum() + "")));

            //判断是否存在赠品/超值换购
            if (!StringUtil.isNullorEmpty(appDetail.getList()) && appDetail.getList().size() > 0) {
                //取出商品, 添加到列表中
                for (TdCommodityUserAppOrderDetailZPRequest gift : appDetail.getList()) {
                    TdCommodityOrderDetails orderDetails2 = new TdCommodityOrderDetails();
                    orderDetails2.setOrderNo(tdCommodityUserOrder.getOrderNo());
                    //换购商品
                    MallGiftCommodity mallDetail2 = mallGiftCommodityService.selectTypeIdByGiftId(gift.getCommodityId());
                    orderDetails2.setCommodityPrice(mallDetail2.getPrice());
                    orderDetails2.setCommodityId(gift.getCommodityId());
                    orderDetails2.setCommodityName(mallDetail2.getCommodityName());
                    orderDetails2.setCommodityNum(gift.getCommodityNum());
                    orderDetails2.setCommodityBarCode(gift.getCommodityBarCode());
                    orderDetails2.setCommoditySpecs(mallDetail2.getSpecs());
                    orderDetails2.setPrice(mallDetail2.getPrice());
                    orderDetails2.setUnderlinedPrice(mallDetail2.getUnderlinedPrice());
                    orderDetails2.setTypeId(mallDetail2.getTypeId());
                    orderDetails2.setGiftType(mallDetail2.getGiftType());
                    orderDetails2.setPicture(mallDetail2.getCover());
                    //查询分类名称
                    MallType mallType = mallGiftCommodityService.findByTypeName(mallDetail2.getTypeId());
                    if (StringUtil.isNullorEmpty(mallType)) {
                        return ResponseData.fail(CodeIdEnum.NoneType);
                    }

                    MallBrand mallBrand = mallGiftCommodityService.findByBrandName(mallDetail2.getBrandId());
                    if (StringUtil.isNullorEmpty(mallType)) {
                        return ResponseData.fail(CodeIdEnum.NoneBrand);
                    }

                    orderDetails2.setTypeName(mallType.getTypeName());
                    orderDetails2.setBrandId(mallDetail2.getBrandId());
                    orderDetails2.setBrandName(mallBrand.getBrandName());
                    orderDetails2.setCommodityTag(gift.getCommodityTag());
                    orderDetails2.setBuyType((byte) 0);
                    orderDetails2.setCode(mallDetail2.getCode());
                    orderDetails2.setOrderStatus((byte) 0);
                    orderDetails2.setCreatedAt(new Date());
                    orderDetails2.setParentId(count);
                    list2.add(orderDetails2);

                    //添加换购商品
                    ActOrderNumReq actOrderNumReq = new ActOrderNumReq();
                    actOrderNumReq.setGiftId(gift.getCommodityId());
                    actOrderNumReq.setGiftName(mallDetail2.getCommodityName());
                    actOrderNumReq.setGiftSpecs(mallDetail2.getSpecs());
                    actOrderNumReq.setNum(gift.getCommodityNum());
                    actOrderNumReq.setTypeId(mallDetail.getTypeId());
                    actOrderNumReq.setStoreId(req.getStoreId());
                    actOrderNumReq.setOrderNo(orderNo);
                    actOrderNumReqList.add(actOrderNumReq);

                    totalAmount = totalAmount.add(orderDetails2.getCommodityPrice().multiply(new BigDecimal(orderDetails2.getCommodityNum() + "")));

                    //添加换购商品物流
                    if (gift.getIsExpress()) {
                        TdCommodityUserGiftRecord giftRecord = new TdCommodityUserGiftRecord();
                        giftRecord.setOrderNo(orderNo);
                        giftRecord.setUserInfoId(userInfoId);
                        giftRecord.setUsName(mailAddressResp.getUserName());
                        giftRecord.setUsPhoneNo(mailAddressResp.getUserPhone());
                        giftRecord.setGiftAddress(mailAddressResp.getAddress() +
                                (StringUtils.isEmpty(mailAddressResp.getDoorplate()) ? "" : mailAddressResp.getDoorplate()));

                        giftRecord.setCreatedAt(new Date());
                        giftRecord.setAgentId(sysStoreOrderDetailResp.getAgentId());
                        giftRecord.setAreaId(sysStoreOrderDetailResp.getAreaId());
                        giftRecord.setCommodityName(mallDetail2.getCommodityName());
                        giftRecord.setCommodityNum(gift.getCommodityNum());
                        giftRecord.setCommoditySpecs(mallDetail2.getSpecs());
                        giftRecord.setCommodityPrice(mallDetail2.getPrice());
                        list3.add(giftRecord);
                    }

                }
            }
            count++;
        }

        tdCommodityUserOrder.setTotalAmount(totalAmount);
        tdCommodityUserOrder.setDiscountAmount(discountAmount);
        tdCommodityUserOrder.setActualAmount(totalAmount.subtract(discountAmount));


        //优惠券相关
        TdCouponUseRecord tdCouponUseRecord = null;
        if(!StringUtils.isEmpty(req.getCode())){
            //查询领取记录
            ActCouponGetRecord actCouponGetRecord = actCouponUserService.selectGetRecordByCodeAndStatusAndDate(req.getCode());

            //判断用户优惠券
            ResponseData couponResp2 = checkCode(actCouponGetRecord, userInfoId,sysAgentInfo.getId(), req.getStoreId(),totalAmount);
            if(couponResp2.getCodeId() != 1){
                return couponResp2;
            }

/*            Long level = userInfoService.selectByLoginId(userInfoId);
            if (!StringUtils.isEmpty(actCouponGetRecord) && (actCouponGetRecord.getLevel() > level)){
                return ResponseData.fail("会员等级未达到使用要求");
            }*/

            tdCouponUseRecord = new TdCouponUseRecord();
            tdCouponUseRecord.setOrderNo(tdCommodityUserOrder.getOrderNo());
            tdCouponUseRecord.setUserInfoId(tdCommodityUserOrder.getUserInfoId());
            LoginInfoResp loginInfoResp = userInfoService.getUserInfoByUserInfoId(tdCommodityUserOrder.getUserInfoId());
            if(!StringUtils.isEmpty(loginInfoResp)){
                tdCouponUseRecord.setUsName(loginInfoResp.getPetName());
                tdCouponUseRecord.setPhoneNo(loginInfoResp.getPhoneNo());
            }
            tdCouponUseRecord.setCode(req.getCode());
            tdCouponUseRecord.setActivityId(actCouponGetRecord.getActivityId());
            tdCouponUseRecord.setActivityName(actCouponGetRecord.getActivityName());
            tdCouponUseRecord.setAmount(actCouponGetRecord.getAmount());
            tdCouponUseRecord.setCouponType(actCouponGetRecord.getCouponType());
            tdCouponUseRecord.setStatus((byte) 0);
            tdCouponUseRecord.setCreatedAt(new Date());

/*            ActUserCouponResp couponResp = actCouponService.selectByCode(req.getCode());
            if(StringUtils.isEmpty(couponResp)){
                return ResponseData.fail("找不到优惠券");
            }*/



            if (actCouponGetRecord.getCouponType() == 1){
                tdCommodityUserOrder.setDiscountAmount(actCouponGetRecord.getAmount());
                tdCommodityUserOrder.setActualAmount(BigDecimal.valueOf(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getDiscountAmount()).doubleValue()));
            } else if (actCouponGetRecord.getCouponType() == 0) {
                tdCommodityUserOrder.setActualAmount(BigDecimal.valueOf(tdCommodityUserOrder.getTotalAmount().multiply(actCouponGetRecord.getAmount().multiply(new BigDecimal("0.1"))).doubleValue()));
                tdCommodityUserOrder.setDiscountAmount(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getActualAmount()));
            }

            if (!StringUtils.isEmpty(actCouponGetRecord.getMaxDiscountAmount())){
                //判断优惠金额大于最多抵扣金额
                if (tdCommodityUserOrder.getDiscountAmount().compareTo(BigDecimal.valueOf(actCouponGetRecord.getMaxDiscountAmount())) > 0) {
                    tdCommodityUserOrder.setDiscountAmount(BigDecimal.valueOf(actCouponGetRecord.getMaxDiscountAmount()));
                    tdCommodityUserOrder.setActualAmount(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getDiscountAmount()));
                }
            }

            //判断优惠金额大于总金额
            if(tdCommodityUserOrder.getTotalAmount().compareTo(tdCommodityUserOrder.getDiscountAmount()) < 0) {
                tdCommodityUserOrder.setDiscountAmount(tdCommodityUserOrder.getTotalAmount());
                tdCommodityUserOrder.setActualAmount(new BigDecimal("0"));
            }

            log.info("优惠券优惠日志,data={}", JSONObject.toJSON(tdCommodityUserOrder));


            tdCouponUseRecord.setDiscountAmount(tdCommodityUserOrder.getDiscountAmount());
            tdCouponUseRecord.setActualAmount(tdCommodityUserOrder.getActualAmount());
            tdCouponUseRecord.setTotalAmount(tdCommodityUserOrder.getTotalAmount());
        }

        //添加下单数据
        ResponseData respData = tdCommodityUserOrderService.placeOrder(tdCommodityUserOrder, list, list2, list3, userInfoId);
        if (respData.getCodeId() != 1) {
            return respData;
        }

        //List<ActOrderNumReq> actOrderNumReqList 换购商品列表
        if (!StringUtils.isEmpty(actOrderNumReqList) && actOrderNumReqList.size() > 0) {
            actGiftService.updateActByOrder(actOrderNumReqList);
        }

        if (respData.getCodeId() == 1 && !StringUtils.isEmpty(req.getCode()) && !StringUtils.isEmpty(tdCouponUseRecord)){
            //插入优惠券记录
            useCoupon2(tdCouponUseRecord);
        }

        //减去购物车中的商品
        if (req.getIsBuyCar() == 1) {
            List<TdBuyCarDetail> delList = new ArrayList<>();

            for (TdCommodityUserAppOrderDetailRequest td1 : req.getList()) {
                TdBuyCarDetail tdBuyCarDetail = new TdBuyCarDetail();
                tdBuyCarDetail.setCommodityId(td1.getCommodityId());
                tdBuyCarDetail.setBuyType(td1.getBuyType());
                tdBuyCarDetail.setCommodityTag((byte) 0);
                tdBuyCarDetail.setCommodityBarCode(td1.getCommodityBarCode());
                tdBuyCarDetail.setParentId(0L);
                delList.add(tdBuyCarDetail);
            }

            //查找对应商品id,并删除
            tdCommodityUserOrderService.delShoppingCarByMoreCondition(delList, req.getStoreId(), userInfoId);

        }

        //添加到定时mq中
        producerMsg.sendPalceOrderMq(tdCommodityUserOrder.getOrderNo(), 16);
        HashMap<String, String> map = new HashMap<>();
        map.put("typeId", MsgTemplatesEnum.CANCEL_ORDER.getTypeId().toString());
        map.put("orderNo", tdCommodityUserOrder.getOrderNo());
        producerMsg.sendMsgOrderMq(map, 15);

        Map<String, String> customParam = MapBuilder.create(new HashMap<String, String>()).put("payMode", EnumPayMode.PAY_COMSUME.getValue()).put("payWay", "2").build();
        String passbackParams = MapUtil.sortJoin(customParam, StrUtil.COMMA, StrUtil.DASHED, false);

        //接入支付宝/微信接口
        //发起交易, 选择支付方式, 1-微信,  发起类型: 交易类型: 0-小程序, 1-app

        ResponseData responseData = null;
        //判断实际支付金额为0
        if(tdCommodityUserOrder.getActualAmount().compareTo(new BigDecimal("0")) == 0){
            //直接支付成功
            payOrderFinish(tdCommodityUserOrder.getOrderNo(),null,(byte) 1);
            responseData = ResponseData.success();
        }else{
            //微信
            if(!StringUtils.isEmpty(req.getTestFlag()) && req.getTestFlag().equals("1")){
                responseData = ResponseData.success(tdCommodityUserOrder.getOrderNo());
            }else{
                if (req.getTradeType() == 0) {
                    //小程序
                    responseData = WechatUtil.wechatUnifiedorder(wechatConfig, tdCommodityUserOrder.getActualAmount(), tdCommodityUserOrder.getOrderNo(), 2, req.getOpenId(), passbackParams);
                } else {
                    //app下单
                    responseData = WechatUtil.wechatAppOrder(wechatConfig, tdCommodityUserOrder.getActualAmount(), tdCommodityUserOrder.getOrderNo(), 1, null, passbackParams);
                }
            }
        }


        if(responseData.getCodeId() != 1){
            return responseData;
        }


        Map map1 = new HashMap();
        map1.put("orderNo", tdCommodityUserOrder.getOrderNo());
        map1.put("payData", responseData.getResData());

        return ResponseData.success(map1);

    }

    // 校验优惠券信息
    private ResponseData checkCode(ActCouponGetRecord actCouponGetRecord,Long userInfoId,Long agentId, Long storeId,BigDecimal totalAmount){

        if(StringUtils.isEmpty(actCouponGetRecord)){
            return ResponseData.fail("优惠券不存在");
        }
        //判断是用户优惠券还是门店优惠券
        if(actCouponGetRecord.getTarget() == 0){
            //判断是否是该用户的优惠券
            if(!actCouponGetRecord.getUserStoreId().equals(userInfoId)){
                return ResponseData.fail("优惠券不存在");
            }
        }else{
            //判断门店是否还能使用优惠券, 根据门店使用次数
            int storeCount = actCouponUserService.countUsedCouponByStoreId(actCouponGetRecord.getActivityId(),storeId);
            if(storeCount >= actCouponGetRecord.getGetQuantity()){
                return ResponseData.fail("优惠券已使用完");
            }
        }
        //判断使用范围是否满足条件
        List<Long> list = JSONArray.parseArray(actCouponGetRecord.getUseScope(),Long.class);
        boolean flag = list.contains(agentId);
        if(!flag){
            return ResponseData.fail("该门店不能使用该优惠券");
        }

        //判断金额是否满足条件
        if(totalAmount.longValue() < actCouponGetRecord.getMinConsumeAmount() ){
            return ResponseData.fail("不满足最低消费金额");
        }

        return ResponseData.success();
    }


/*    @Log
    @Token
    @ApiOperation("test")
    @PostMapping("/test")
    public ResponseData paytest(String code, Long store, Long userInfoId) throws Exception {
        TdCommodityUserOrder tdCommodityUserOrder = new TdCommodityUserOrder();
        tdCommodityUserOrder.setTotalAmount(new BigDecimal(137700));
        ActUserCouponResp couponResp = actCouponService.selectByCode(code);

        if (couponResp.getCouponType() == 1) {
            tdCommodityUserOrder.setDiscountAmount(couponResp.getAmount().multiply(new BigDecimal(100)));
            tdCommodityUserOrder.setActualAmount(BigDecimal.valueOf(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getDiscountAmount()).doubleValue()));
        } else if (couponResp.getCouponType() == 0) {
            tdCommodityUserOrder.setActualAmount(BigDecimal.valueOf(tdCommodityUserOrder.getTotalAmount().multiply(couponResp.getAmount().multiply(new BigDecimal(0.1))).doubleValue()));
            tdCommodityUserOrder.setDiscountAmount(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getActualAmount()));
            if (tdCommodityUserOrder.getDiscountAmount().compareTo(new BigDecimal(100000)) == 1) {
                tdCommodityUserOrder.setDiscountAmount(new BigDecimal(100000));
                tdCommodityUserOrder.setActualAmount(tdCommodityUserOrder.getTotalAmount().subtract(tdCommodityUserOrder.getDiscountAmount()));
            }
        }
        System.out.println(tdCommodityUserOrder.getDiscountAmount());
        System.out.println(tdCommodityUserOrder.getActualAmount());
        //Long userInfoId = Long.parseLong(getAttribute());
        ActCouponCountResp resp = actCouponUserService.selectCodeLoginId(userInfoId, code);
        if (ObjectUtils.isEmpty(resp)) {
            Long storeId = actCouponUserService.findCouponStoreId(code);
            if (!StringUtils.isEmpty(storeId)) {
                if (!store.equals(storeId)) {
                    return ResponseData.fail("此优惠券只能在指定门店使用");
                }
            }
        }
        Long level = userInfoService.selectByLoginId(userInfoId);
        if (resp.getLevel() > level) {
            return ResponseData.fail("会员等级未达到使用要求");
        }
        return null;
    }*/

    @Log
    @Token
    @ApiOperation("用户支付接口")
    @PostMapping("/pay")
    public ResponseData pay(@RequestBody TdCommodityUserAppPayOrderRequest req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        if (req.getTradeType() == 0) {
            if (StringUtil.isNullorEmpty(req.getOpenId())) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), "用户标识ID不能为空");
            }
        }

        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderService.findByOrderNo(req.getOrderNo());

        if (StringUtil.isNullorEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //判断门店
        SysStoreOrderDetailResp sysStoreOrderDetailResp = sysStoreInfoService.findOrderDetailByStoreId(tdCommodityUserOrder.getStoreId());
        if (StringUtil.isNullorEmpty(sysStoreOrderDetailResp)) {
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        if (sysStoreOrderDetailResp.getStatus() == -1){
            return ResponseData.fail(CodeIdEnum.STOREClOSEDINFO);
        }
        //判断代理商
        SysAgentInfo sysAgentInfo = sysAgentInfoService.selectSysAgentInfo(sysStoreOrderDetailResp.getAgentId());
        if (ObjectUtils.isEmpty(sysAgentInfo)) {
            return ResponseData.fail(CodeIdEnum.NOAGENT);
        }
        if (sysAgentInfo.getStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.AGENTSTOP);
        }
        //根据订单号查询优惠券记录, 判断该订单是否使用了优惠券
        TdCouponUseRecord tdCouponUseRecord = tdCouponUseService.selectByOrderNo(req.getOrderNo());
        if(!StringUtils.isEmpty(tdCouponUseRecord)){
            //查询领取记录
            ActCouponGetRecord actCouponGetRecord = actCouponUserService.selectGetRecordByCodeAndStatusAndDate(tdCouponUseRecord.getCode());
            //判断优惠券状态
            if(StringUtils.isEmpty(actCouponGetRecord)){
                return ResponseData.fail("订单优惠券不存在");
            }
            //校验优惠券
            ResponseData couponResp = checkCode(actCouponGetRecord,tdCommodityUserOrder.getUserInfoId(),tdCommodityUserOrder.getAgentId(), tdCommodityUserOrder.getStoreId(),tdCommodityUserOrder.getTotalAmount());
            if(couponResp.getCodeId() != 1){
                return couponResp;
            }
        }


        //判断商品
        List<TdCommodityOrderDetails> commodityList = tdCommodityUserOrderService.findCommodityByOrderNo(tdCommodityUserOrder.getOrderNo(), (byte) 0);
        for (TdCommodityOrderDetails com1 : commodityList) {
            CommodityOrderDetailResp mallDetail = mallCommodityService.findOrderDetailByCommodityId(com1.getCommodityId());
            if (StringUtil.isNullorEmpty(mallDetail)) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }
            if (mallDetail.getCommodityStatus() == -2){
                return ResponseData.fail(CodeIdEnum.DOWNPRODUCT);
            }
            if (mallDetail.getCommodityStatus() != 3) {
                return ResponseData.fail(CodeIdEnum.NOCOMMODITYSTATUS);
            }
            boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreOrderDetailResp.getAgentId(), com1.getCommodityId());
            if (!b6) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }

            //判断换购商品
            List<TdCommodityOrderDetails> hgList = tdCommodityUserOrderService.findTdOrderDetailByParentId(com1.getId(), (byte) 2);
            for (TdCommodityOrderDetails com2 : hgList) {
                //判断赠品的状态
                MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(com2.getCommodityId());

                if (StringUtil.isNullorEmpty(mallGiftCommodity)) {
                    return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                }

                boolean b4 = actGiftService.checkGift(mallDetail.getTypeId(), com2.getCommodityId(), tdCommodityUserOrder.getStoreId());
                if (!b4) {
                    return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                }
            }
        }

        Map<String, String> customParam = MapBuilder.create(new HashMap<String, String>()).put("payMode", EnumPayMode.PAY_COMSUME.getValue()).put("payWay", "2").build();
        String passbackParams = MapUtil.sortJoin(customParam, StrUtil.COMMA, StrUtil.DASHED, false);


        //微信
        if (req.getTradeType() == 0) {
            //小程序
            ResponseData responseData = WechatUtil.wechatUnifiedorder(wechatConfig, tdCommodityUserOrder.getActualAmount(), tdCommodityUserOrder.getOrderNo(), 2, req.getOpenId(), passbackParams);
            return responseData;
        } else {
            //app下单
            ResponseData responseData = WechatUtil.wechatAppOrder(wechatConfig, tdCommodityUserOrder.getActualAmount(), tdCommodityUserOrder.getOrderNo(), 1, null, passbackParams);
            return responseData;
        }

    }

    public void useCoupon2(TdCouponUseRecord tdCouponUseRecord){
        //插入记录
        tdCouponUseService.insert(tdCouponUseRecord);
    }

    @Log
    @Token
    @ApiOperation("删除购物车列表")
    @PostMapping("/delBuyCarList")
    public ResponseData removeBuyCarList(@RequestBody TdCommodityDelBuyCarReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        return tdCommodityUserOrderService.removeShoppingCar(req.getIds(), Long.parseLong(getAttribute()));
    }

    @Log
    @ApiOperation("新增/更新购物车")
    @Token
    @PostMapping("insertShoppingCar")
    @ApiOperationSupport(ignoreParameters = {"typeId"})
    public ResponseData insertShoppingCar(@RequestBody TdBuyCarInsertReq req) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        //判断商品不能为空
        if (StringUtil.isNullorEmpty(req.getList()) || req.getList().isEmpty()) {
            return ResponseData.fail(CodeIdEnum.NonCommodity);
        }
        for (TdBuyCarDetailInsertReq tdBuyCarDetailInsertReq : req.getList()) {
            ConstraintViolation validate2 = BeanValidator.validate(tdBuyCarDetailInsertReq);
            if (validate2 != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate2.getMessage());
            }
        }

        //校验商品不重复, 商品id,barCode, 购买方式
        List<TdBuyCarDetailInsertReq> tdReq1 = req.getList();
        List<TdBuyCarDetailInsertReq> tdReq2 = req.getList();
        int count1 = 0;
        for (TdBuyCarDetailInsertReq reReq1 : tdReq1) {
            int count2 = 0;
            for (TdBuyCarDetailInsertReq reReq2 : tdReq2) {
                if (count1 != count2 && reReq1.getCommodityBarCode().equals(reReq2.getCommodityBarCode()) && Objects.equals(reReq1.getCommodityId(), reReq2.getCommodityId()) &&
                        Objects.equals(reReq1.getBuyType(), reReq2.getBuyType())) {
                    return ResponseData.fail(CodeIdEnum.RepeatMall);
                }
                count2++;
            }
            count1++;

            //校验赠品不重复
/*            if(!StringUtils.isEmpty(reReq1.getList()) && reReq1.getList().size() > 0){
                List<Long> reZPIdsList = reReq1.getList().stream().map(TdBuyCarDetailZpInsertReq::getCommodityId).collect(Collectors.toList());
                HashSet reZpIdsSet = new HashSet(reZPIdsList);
                if(reZpIdsSet.size() < reZPIdsList.size()){
                    return ResponseData.fail(CodeIdEnum.RepeatMall);
                }
            }*/
        }

        TdCommodityBuyCardRequest tdReq = new TdCommodityBuyCardRequest();
        tdReq.setStoreId(req.getStoreId());
        SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(req.getStoreId());
        if (StringUtils.isEmpty(sysStoreInfo)) {
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        tdReq.setStoreName(sysStoreInfo.getStoreName());
        tdReq.setCarStatus(req.getCarStatus());
        List<TdCommodityBuyCardDetailRequest> tdReqList = new ArrayList<>();

        for (TdBuyCarDetailInsertReq tdBuyCarDetailInsertReq : req.getList()) {
            //判断是否为更新购物车, 判断id
            if (req.getCarStatus() == 0) {
                if (StringUtil.isNullorEmpty(tdBuyCarDetailInsertReq.getId())) {
                    return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "更新购物车时id不能为空");
                }
            }
            //判断商品是否上架
            MallCommodityWithBLOBs mallCommodityWithBLOBs = mallCommodityService.selectByPrimaryKey(tdBuyCarDetailInsertReq.getCommodityId());
            if (StringUtils.isEmpty(mallCommodityWithBLOBs) || mallCommodityWithBLOBs.getCommodityStatus() != 3) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }

            //判断商品是否可以以旧换新
            if (tdBuyCarDetailInsertReq.getBuyType() == 1) {
                if (mallCommodityWithBLOBs.getIsInNew() != 0) {
                    return ResponseData.fail(CodeIdEnum.NONeIsInNew);
                }
            }

            boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreInfo.getSysAgentInfoId(), tdBuyCarDetailInsertReq.getCommodityId());
            if (!b6) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }

            TdCommodityBuyCardDetailRequest detailRequest2 = new TdCommodityBuyCardDetailRequest();
            BeanUtils.copyProperties(tdBuyCarDetailInsertReq, detailRequest2);
            detailRequest2.setCommodityName(mallCommodityWithBLOBs.getCommodityName());
            detailRequest2.setTypeId(mallCommodityWithBLOBs.getTypeId());

            //查询商品规格表信息
            MallCommoditySpecs mallCommoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(tdBuyCarDetailInsertReq.getCommodityId(), tdBuyCarDetailInsertReq.getCommodityBarCode());
            if (!StringUtil.isNullorEmpty(mallCommoditySpecs)) {
                detailRequest2.setPicture(mallCommoditySpecs.getPicture());
                //购买方式,  0-直接买新, 1-以旧换新
                if (tdBuyCarDetailInsertReq.getBuyType() == 0) {
                    detailRequest2.setCommodityPrice(mallCommoditySpecs.getPrice());
                } else {
                    detailRequest2.setCommodityPrice(mallCommoditySpecs.getInNewPrice());
                }
            } else {
                detailRequest2.setPicture(mallCommodityWithBLOBs.getCover());
                if (tdBuyCarDetailInsertReq.getBuyType() == 0) {
                    detailRequest2.setCommodityPrice(mallCommodityWithBLOBs.getPrice());
                } else {
                    detailRequest2.setCommodityPrice(mallCommodityWithBLOBs.getInNewPrice());
                }
            }
            detailRequest2.setUnderlinedPrice(mallCommodityWithBLOBs.getUnderlinedPrice());
            detailRequest2.setCommodityTag((byte) 0);

/*            if (!StringUtils.isEmpty(tdBuyCarDetailInsertReq.getList()) && tdBuyCarDetailInsertReq.getList().size() > 0) {
                List<TdCommodityBuyCardDetailZPRequest> tdReqZpList = new ArrayList<>();

                for (TdBuyCarDetailZpInsertReq zpRequest : tdBuyCarDetailInsertReq.getList()) {
                    TdCommodityBuyCardDetailZPRequest tdReqZp = new TdCommodityBuyCardDetailZPRequest();

                    BeanUtils.copyProperties(zpRequest, tdReqZp);
                    //判断换购商品的状态
                    //查询换购商品的分类id
                    MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(zpRequest.getCommodityId());

                    if(StringUtil.isNullorEmpty(mallGiftCommodity)){
                        return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                    }

                    boolean b4 = actGiftService.checkGift(mallCommodityWithBLOBs.getTypeId(),zpRequest.getCommodityId(), req.getStoreId());
                    if (!b4) {
                        return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                    }
                    tdReqZp.setTypeId(mallGiftCommodity.getTypeId());
                    tdReqZp.setPicture(mallGiftCommodity.getCover());
                    tdReqZp.setCommodityName(mallGiftCommodity.getCommodityName());
                    tdReqZp.setCommodityBarCode(mallGiftCommodity.getSpecsCode());
                    tdReqZp.setCommodityPrice(mallGiftCommodity.getPrice());
                    tdReqZp.setUnderlinedPrice(mallGiftCommodity.getUnderlinedPrice());
                    tdReqZp.setCommoditySpecs(mallGiftCommodity.getSpecs());
                    tdReqZp.setBuyType((byte) 0);

                    tdReqZpList.add(tdReqZp);

                }

                detailRequest2.setList(tdReqZpList);
            }*/
            tdReqList.add(detailRequest2);
        }
        tdReq.setList(tdReqList);

        return tdCommodityUserOrderService.addShoppingCar(tdReq, Long.parseLong(getAttribute()));
    }

    @Log
    @ApiOperation("查询购物车列表")
    @Token
    @GetMapping("findBuyCars")
    public ResponseData<TdBuyCardListResp> findBuyCars(TdBuyCarStoreIdReq tdBuyCarStoreIdReq) throws Exception {

        Long userInfoId = Long.parseLong(getAttribute());
        TdBuyCardListResp tdBuyCardListResp = new TdBuyCardListResp();
        List<TdBuyCarResp> buycarList = new ArrayList<>();
        List<TdBuyCarDetailLoseResp> loseCommodityList = new ArrayList<>();

        List<TdBuyCarResp> tdBuyCarRespList = tdCommodityUserOrderService.selectByUserInfoId(userInfoId, tdBuyCarStoreIdReq.getStoreId());

        if (StringUtil.isNullorEmpty(tdBuyCarRespList) || tdBuyCarRespList.size() <= 0) {
            return ResponseData.success(tdBuyCardListResp);
        }

        for (TdBuyCarResp tdBuyCarResp : tdBuyCarRespList) {
            SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(tdBuyCarResp.getStoreId());
            if (StringUtils.isEmpty(sysStoreInfo)) {
                return ResponseData.fail(CodeIdEnum.NonStoreInfo);
            }
            List<TdBuyCarDetailResp> detailList = tdCommodityUserOrderService.selectBuyCarDetailList(tdBuyCarResp.getId(), "0");
            if (StringUtil.isNullorEmpty(detailList) || detailList.size() <= 0) {
                continue;
            }
            Iterator<TdBuyCarDetailResp> iterator = detailList.iterator();
            while (iterator.hasNext()) {
                TdBuyCarDetailResp tdBuyCarDetailResp = iterator.next();
                boolean b2 = mallCommodityService.isUpShelf(tdBuyCarDetailResp.getCommodityId());

                boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreInfo.getSysAgentInfoId(), tdBuyCarDetailResp.getCommodityId());

                if (!b2 || !b6) {
                    TdBuyCarDetailLoseResp tdBuyCarDetailLoseResp = new TdBuyCarDetailLoseResp();
                    BeanUtils.copyProperties(tdBuyCarDetailResp, tdBuyCarDetailLoseResp);
                    loseCommodityList.add(tdBuyCarDetailLoseResp);
                    iterator.remove();
                    continue;
                }
                //判断该商品下是否能换购商品
/*                boolean giftFlag = actGiftService.isGiftByTypeId(tdBuyCarDetailResp.getTypeId(), tdBuyCarResp.getStoreId());
                if(giftFlag){
                    tdBuyCarDetailResp.setGiftFlag((byte) 1);
                }else{
                    tdBuyCarDetailResp.setGiftFlag((byte) 0);
                }*/
                //查找赠品
/*                List<TdBuyCarDetailZpResp> zpList = tdCommodityUserOrderService.selectZPByBuyCarIdAndParentId(tdBuyCarResp.getId(), tdBuyCarDetailResp.getId());
                Iterator<TdBuyCarDetailZpResp> iteratorZP = zpList.iterator();
                while (iteratorZP.hasNext()) {
                    TdBuyCarDetailZpResp tdBuyCarDetailZpResp = iteratorZP.next();
                    MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(tdBuyCarDetailZpResp.getCommodityId());
                    boolean b4 = !StringUtil.isNullorEmpty(mallGiftCommodity);

                    if(b4){
                        b4 = actGiftService.checkGift(tdBuyCarDetailResp.getTypeId(),tdBuyCarDetailZpResp.getCommodityId(), tdBuyCarResp.getStoreId());
                    }

                    if (!b4) {
                        TdBuyCarDetailLoseResp tdBuyCarDetailLoseResp2 = new TdBuyCarDetailLoseResp();
                        BeanUtils.copyProperties(tdBuyCarDetailZpResp, tdBuyCarDetailLoseResp2);
                        loseCommodityList.add(tdBuyCarDetailLoseResp2);
                        iteratorZP.remove();
                        continue;
                    }
                }
                tdBuyCarDetailResp.setList(zpList);*/
            }

            if (StringUtil.isNullorEmpty(detailList) || detailList.size() <= 0) {
                continue;
            }

            tdBuyCarResp.setList(detailList);
            buycarList.add(tdBuyCarResp);
        }

        tdBuyCardListResp.setBuycardList(buycarList);
        tdBuyCardListResp.setLoseCommodityList(loseCommodityList);
        return ResponseData.success(tdBuyCardListResp);
    }


    @Log
    @ApiOperation("删除无效商品")
    @Token
    @PostMapping("deleLoseCar")
    public ResponseData removeLoseCar() {
        Long userInfoId = Long.parseLong(getAttribute());

        List<Long> ids = new ArrayList<>();

        List<TdBuyCarResp> tdBuyCarRespList = tdCommodityUserOrderService.selectByUserInfoId(userInfoId, null);
        if (!StringUtils.isEmpty(tdBuyCarRespList) && tdBuyCarRespList.size() > 0) {
            for (TdBuyCarResp tdBuyCarResp : tdBuyCarRespList) {
                SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKey(tdBuyCarResp.getStoreId());
                if (StringUtils.isEmpty(sysStoreInfo)) {
                    return ResponseData.fail(CodeIdEnum.NonStoreInfo);
                }

                List<TdBuyCarDetailResp> detailList = tdCommodityUserOrderService.selectBuyCarDetailList(tdBuyCarResp.getId(), "0");
                for (TdBuyCarDetailResp tdBuyCarDetailResp : detailList) {
                    boolean b2 = mallCommodityService.isUpShelf(tdBuyCarDetailResp.getCommodityId());

                    boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreInfo.getSysAgentInfoId(), tdBuyCarDetailResp.getCommodityId());

                    if (!b2 || !b6) {
                        ids.add(tdBuyCarDetailResp.getId());
                        //删除该商品下的赠品
/*                        List<Long> zpIds = tdCommodityUserOrderService.selectZPIdsByParentId(tdBuyCarDetailResp.getId());
                        if(!StringUtils.isEmpty(zpIds) && zpIds.size() > 0){
                            ids.addAll(zpIds);
                        }*/
                    }
                }
                //校验换购商品
/*                List<TdBuyCarDetailDelResp> detailZPList = tdCommodityUserOrderService.selectBuyCarDetailZPList(tdBuyCarResp.getId(), "0");
                for(TdBuyCarDetailDelResp tdBuyCarDetailZP:detailZPList){
                    TdBuyCarDetail tdBuyCarDetail = tdCommodityUserOrderService.findTdBuyCarDetailByParentId(tdBuyCarDetailZP.getParentId());
                    boolean b4 = false;
                    if(null != tdBuyCarDetail){
                         b4 = actGiftService.checkGift(tdBuyCarDetail.getTypeId(),tdBuyCarDetailZP.getCommodityId(), tdBuyCarResp.getStoreId());
                    }
                    if(!b4){
                        ids.add(tdBuyCarDetailZP.getId());
                    }
                }*/
            }
            if (ids.size() > 0) {
                //id去重
                HashSet h = new HashSet(ids);
                ids.clear();
                ids.addAll(h);
                return tdCommodityUserOrderService.removeShoppingCar(ids, userInfoId);
            }
        }

        return ResponseData.success();


    }


    @Log
    @ApiOperation("清空购物车")
    @Token
    @PostMapping("clearCar")
    public ResponseData clearCar() {
        Long userInfoId = Long.parseLong(getAttribute());
        List<Long> ids = new ArrayList<>();

        List<TdBuyCarResp> tdBuyCarRespList = tdCommodityUserOrderService.selectByUserInfoId(userInfoId, null);
        for (TdBuyCarResp tdBuyCarResp : tdBuyCarRespList) {
            List<TdBuyCarDetailResp> detailList = tdCommodityUserOrderService.selectBuyCarDetailList(tdBuyCarResp.getId(), null);
            for (TdBuyCarDetailResp tdBuyCarDetailResp : detailList) {
                ids.add(tdBuyCarDetailResp.getId());
            }
        }
        return tdCommodityUserOrderService.removeShoppingCar(ids, userInfoId);
    }

    //新增/更新
    @Log
    @ApiOperation("新增/更新 换购商品")
    @Token
    @PostMapping("addZPShoppingCar")
    @ApiIgnore
    public ResponseData addZPShoppingCar(@RequestBody TdBuyCarDetailZpEditReq req) {
        ConstraintViolation validate2 = BeanValidator.validate(req);
        if (validate2 != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate2.getMessage());
        }

        if (StringUtils.isEmpty(req.getZpList()) || req.getZpList().size() <= 0) {
            return tdCommodityUserOrderService.delZpByParentId(req.getId());
        }

        //校验换购商品是否重复数据
        List<Long> reZPIdsList = req.getZpList().stream().map(TdBuyCarDetailZPListReq::getCommodityId).collect(Collectors.toList());
        HashSet reZpIdsSet = new HashSet(reZPIdsList);
        if (reZpIdsSet.size() < reZPIdsList.size()) {
            return ResponseData.fail(CodeIdEnum.RepeatMall);
        }

        TdBuyCar tdBuyCar = tdCommodityUserOrderService.findTdBuyCarBybuyCarId(req.getBuyCarId());
        if (StringUtils.isEmpty(tdBuyCar)) {
            return ResponseData.fail(CodeIdEnum.NoneBUYCAR);
        }

        TdBuyCarDetail tdBuyCarDetail = tdCommodityUserOrderService.findTdBuyCarDetailById(req.getId());

        if (StringUtils.isEmpty(tdBuyCarDetail)) {
            return ResponseData.fail(CodeIdEnum.NONETDBUYCAR);
        }

        List<TdBuyCarDetailZPListReq> zpList = req.getZpList();
        for (TdBuyCarDetailZPListReq zpReq : zpList) {
            ConstraintViolation validate = BeanValidator.validate(zpReq);
            if (validate != null) {
                return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
            }
            //判断赠品的状态
            MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(zpReq.getCommodityId());

            if (StringUtil.isNullorEmpty(mallGiftCommodity)) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
            }

            boolean b4 = actGiftService.checkGift(tdBuyCarDetail.getTypeId(), zpReq.getCommodityId(), tdBuyCar.getStoreId());
            if (!b4) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
            }
        }

        List<TdAddUpdateBuyCarDetailZPReq> zpList2 = new ArrayList<>();

        for (TdBuyCarDetailZPListReq zpReq : zpList) {
            MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(zpReq.getCommodityId());

            if (StringUtil.isNullorEmpty(mallGiftCommodity)) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
            }
            TdAddUpdateBuyCarDetailZPReq td2 = new TdAddUpdateBuyCarDetailZPReq();
            td2.setId(zpReq.getId());
            td2.setCommodityId(zpReq.getCommodityId());
            td2.setCommodityName(mallGiftCommodity.getCommodityName());
            td2.setCommodityBarCode(mallGiftCommodity.getSpecsCode());
            td2.setCommoditySpecs(mallGiftCommodity.getSpecs());
            td2.setPicture(mallGiftCommodity.getCover());
            td2.setCommodityNum(zpReq.getCommodityNum());
            td2.setCommodityTag(zpReq.getCommodityTag());
            td2.setParentId(req.getId());
            td2.setBuyCarId(req.getBuyCarId());
            td2.setCommodityPrice(mallGiftCommodity.getPrice());
            td2.setUnderlinedPrice(mallGiftCommodity.getUnderlinedPrice());

            zpList2.add(td2);
        }
        return tdCommodityUserOrderService.addZPShoppingCar(zpList2);
    }

    @Log
    @ApiOperation("用户订单列表")
    @Token
    @GetMapping("list")
    public ResponseData<PageInfo<TdCommodityAppOrderListResp>> list(TdCommodityUserAppListRequest req) {

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysSystemParam systemParam = systemParamService.findByParamKey(SystemParamsEnum.REFUND_TIME.getValue());

        return tdCommodityUserOrderService.findAppOrderByOrderStatus(req, Long.parseLong(getAttribute()), systemParam.getParamValue());
    }

    @Log
    @ApiOperation("查询单个订单信息")
    @Token
    @GetMapping("findByOrderNo")
    public ResponseData<TdCommodityAppOrderAfterServiceResp> findUserOrderByOrderNo(@ApiParam(required = true, name = "orderNo",
            value = "订单编号") @RequestParam("orderNo") String orderNo) {
        if (StringUtil.isNullorEmpty(orderNo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "订单编号不能为空");
        }

        SysSystemParam systemParam = systemParamService.findByParamKey(SystemParamsEnum.REFUND_TIME.getValue());
        return tdCommodityUserOrderService.findUserOrderByOrderNo(orderNo, Long.parseLong(getAttribute()), systemParam.getParamValue());
    }

    @Log
    @ApiOperation("修改订单地址")
    @Token
    @PostMapping("updateAddress")
    public ResponseData updateOrderAddress(@RequestBody TdCommodityUserAppUpdateAddressRequest req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long userInfoId = Long.parseLong(getAttribute());
        UserAddressResp userAddressResp = userInfoService.findAddressByUserInfoId(req.getAddressId(), userInfoId);
        if (StringUtils.isEmpty(userAddressResp)) {
            return ResponseData.fail(CodeIdEnum.NOADDRESS);
        }

        //根据订单编号修改订单信息
        return tdCommodityUserOrderService.updateOrderAddress(req.getOrderNo(), userAddressResp.getUserName(), userAddressResp.getUserPhone(),
                userAddressResp.getAddress() + (StringUtils.isEmpty(userAddressResp.getDoorplate()) ? "" : userAddressResp.getDoorplate()),
                userAddressResp.getLongitude(), userAddressResp.getLatitude());

    }


    @Log
    @ApiOperation("取消订单")
    @Token
    @PostMapping("cancelOrder")
    public ResponseData cancelOrderByorderNo(@RequestBody TdCommodityCancelReq req) {

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        ResponseData resp = tdCommodityUserOrderService.cancelOrderByorderNo(req.getOrderNo());
        if (resp.getCodeId() == 1) {
            tdCouponUseService.updateStatusByorderNo(req.getOrderNo(), (byte) -1);
        }
        return resp;
    }

    @Log
    @ApiOperation("申请售后")
    @Token
    @PostMapping("applyAfterService")
    public ResponseData applyAfterService(@RequestBody TdCommodityApplyAfterServiceReq req) {

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        SysSystemParam systemParam = systemParamService.findByParamKey(SystemParamsEnum.REFUND_TIME.getValue());

        Long userInfoId = Long.parseLong(getAttribute());
        ResponseData resp = tdCommodityUserOrderService.applyAfterService(req, systemParam.getParamValue(),userInfoId);

        if (resp.getCodeId() == 1) {
            TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderService.findByOrderNo(req.getOrderNo());
            massageTask.storePushOrder(tdCommodityUserOrder.getStoreId(), EnumMsgType.APPLYORDERAFTERSERIVCE.getName(), EnumMsgType.APPLYORDERAFTERSERIVCE.getValue(), tdCommodityUserOrder.getOrderNo());
        }
        return resp;
    }

    @Log
    @ApiOperation("取消售后")
    @Token
    @PostMapping("cancelAfterService")
    public ResponseData cancelAfterService(@RequestBody TdCommodityCancelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        return tdCommodityUserOrderService.cancelAfterService(req);
    }

    @Log
    @ApiOperation("售后记录")
    @Token
    @GetMapping("afterSaleRecord")
    public ResponseData<UserAppAfterSaleRecordResp> afterSaleRecord(){
        Long userInfoId = Long.parseLong(getAttribute());
        UserAppAfterSaleRecordResp userAppAfterSaleRecordResp =tdCommodityUserOrderService.selectByUserInfoId(userInfoId);
        return ResponseData.success(userAppAfterSaleRecordResp);
    }

    /**
     * @param
     * @param
     * @return true可用 false不可用
     */
/*    private boolean checkGift(Long commodityId,Long giftId){
        MallCommodityWithBLOBs commodity = mallCommodityService.selectByPrimaryKey(commodityId);
        if(ObjectUtil.isEmpty(commodity)){
            return false;
        }
        return actGiftService.checkGift(commodity.getTypeId(),giftId);
    }*/

    //订单支付完成, 支付方式, 1-微信, 2-测试,
    public ResponseData payOrderFinish(String orderNo, String otherOrderNo, byte tradeChannel) {
        //查询订单信息
        TdCommodityUserOrder td1 = tdCommodityUserOrderService.findByOrderNo(orderNo);
        if (StringUtil.isNullorEmpty(td1)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        if (td1.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //1.修改该订单信息
        ResponseData resp = tdCommodityUserOrderService.updateOrder(orderNo, otherOrderNo, tradeChannel);
        if (resp.getCodeId() != 1) {
            return resp;
        }

        //使用优惠券
        TdCouponUseRecord record = tdCouponUseService.selectByOrderNo(orderNo);
        if (!ObjectUtils.isEmpty(record)) {
            //判断优惠券状态是否为待付款
            if(record.getStatus() == 0){
                //可以使用优惠券, 调整订单优惠券信息
                tdCouponUseService.updateByIdAndCode(record.getId(),record.getCode());

                //修改code表,
                actCouponUserService.updateActCouponActivityCode(record.getCode(),(byte) 2);
                //修改getRecord表
                //判断是用户优惠券还是门店优惠券
                ActCouponGetRecord actCouponGetRecord = actCouponUserService.selectGetRecordByCode(record.getCode());
                if(!StringUtils.isEmpty(actCouponGetRecord)){
                    ActCouponGetRecord getRecord = new ActCouponGetRecord();
                    getRecord.setId(actCouponGetRecord.getId());
                    getRecord.setStatus((byte) 1);
                    getRecord.setUpdatedAt(new Date());

                    //判断是否是用户还是门店优惠券
                    if(actCouponGetRecord.getTarget() == 1){
                        //门店
                        getRecord.setUserStoreId(td1.getStoreId());
//                        getRecord.setUsUserName(td1.getUsName());
//                        getRecord.setPhoneNo(td1.getUsPhoneNo());
                    }
                    actCouponUserService.updateGetRecord(getRecord);
                    //添加userdRecord表
                    LoginInfoResp loginInfoResp = userInfoService.getUserInfoByUserInfoId(td1.getUserInfoId());
                    ActCouponUsedRecord actCouponUsedRecord = new ActCouponUsedRecord();
                    actCouponUsedRecord.setActivityId(actCouponGetRecord.getActivityId());
                    actCouponUsedRecord.setCode(actCouponGetRecord.getCode());
                    actCouponUsedRecord.setStoreId(td1.getStoreId());
                    actCouponUsedRecord.setUserInfoId(td1.getUserInfoId());
                    if(!StringUtils.isEmpty(loginInfoResp)){
                        actCouponUsedRecord.setUsUserName(loginInfoResp.getPetName());
                        actCouponUsedRecord.setPhoneNo(loginInfoResp.getPhoneNo());
                    }
                    actCouponUsedRecord.setCreatedAt(new Date());
                    actCouponUsedRecord.setIsDeleted((byte) 0);
                    actCouponUserService.insertUsedRecord(actCouponUsedRecord);

                    if(actCouponGetRecord.getTarget() == 1){
                        //进行推送
                        massageTask.storePushOrder(td1.getStoreId(), EnumMsgType.Coupon_used.getName(), EnumMsgType.Coupon_used.getValue(), actCouponGetRecord.getActivityId().toString());
                    }
                }

/*                ActUpdateStatisReq req = new ActUpdateStatisReq();
                req.setActivityId(record.getActivityId());
                req.setDiscountAmount(record.getDiscountAmount());
                req.setPayableAmount(record.getTotalAmount());
                req.setPayAmount(record.getActualAmount());
                actCouponUserService.updateStatis(req);*/
            }


        }

        //添加出库记录, 判断是否到店自取 修改库存
        if (td1.getOrderType() == 1) {
            updateStoreInfo(td1.getOrderNo(), td1.getStoreId());
        }


        //2.修改用户订单数,用户
        TdCommodityUserOrder tdCommodityUserOrder = (TdCommodityUserOrder) resp.getResData();
        ResponseData resp1 = userInfoService.updateUsUserStatis(tdCommodityUserOrder.getUserInfoId(), tdCommodityUserOrder.getActualAmount());
        if (resp1.getCodeId() != 1) {
            return resp1;
        }
        //3.门店
        ResponseData resp2 = sysStoreInfoService.updateStoreOrder(tdCommodityUserOrder.getStoreId(), tdCommodityUserOrder.getActualAmount());
        if (resp2.getCodeId() != 1) {
            return resp2;
        }
        //4.修改用户等级
        SysLevelRule ruleByOrderNum = levelRuleService.findLevelRuleByOrderNum(1L);
        if (!ObjectUtils.isEmpty(ruleByOrderNum)) {
            UsUserAccountInfo accountInfo = new UsUserAccountInfo();
            accountInfo.setUserInfoId(tdCommodityUserOrder.getUserInfoId());
            accountInfo.setLevel(Long.parseLong(ruleByOrderNum.getLevel().toString()));
            accountInfo.setLevelName(ruleByOrderNum.getLevelName());
            accountInfo.setUpdatedAt(new Date());
            userInfoService.updateUserLevel(accountInfo);
        }
        //门店计算积分
        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(tdCommodityUserOrder.getStoreId());
        List<TdCommodityOrderDetails> commodityList = tdCommodityUserOrderService.findCommodityByOrderNo(orderNo, (byte) 0);
        if (CollUtil.isNotEmpty(commodityList)) {
            List<StoreCommodityIntegralDetialReq> comIntReqList = new ArrayList<>();
            BigDecimal decimal = new BigDecimal("0");
            for (TdCommodityOrderDetails orderDetails : commodityList) {
                BigDecimal ruleValue = sysRuleCommodityIntegralService.findRuleValueByIdAndBarCode(orderDetails.getCommodityId(), orderDetails.getCommodityBarCode());
                if (ObjectUtil.isNotEmpty(ruleValue)) {
                    if (ObjectUtil.isNotEmpty(accountInfo)) {
                        for (Integer i = 0; i < orderDetails.getCommodityNum(); i++) {
                            StoreCommodityIntegralDetialReq scidq = new StoreCommodityIntegralDetialReq();
                            scidq.setCommodityName(orderDetails.getCommodityName());
                            scidq.setCommodityId(orderDetails.getCommodityId());
                            scidq.setBarCode(orderDetails.getCommodityBarCode());
                            scidq.setSpecs(orderDetails.getCommoditySpecs());
                            scidq.setIntegral(ruleValue);
                            decimal = decimal.add(ruleValue);
                            comIntReqList.add(scidq);
                        }
                    }
                }
            }
            if (CollUtil.isNotEmpty(comIntReqList)) {
                StoreCommodityIntegralReq intReq = new StoreCommodityIntegralReq();
                intReq.setStoreId(tdCommodityUserOrder.getStoreId());
                intReq.setAccountId(accountInfo.getId());
                intReq.setOrderNo(orderNo);
                intReq.setList(comIntReqList);
                SysStoreAccountInfo acc = new SysStoreAccountInfo();
                acc.setId(accountInfo.getId());
                acc.setPoint(accountInfo.getPoint().add(decimal));
                sysStoreInfoService.updateAccountInfo(acc);
                intReq.setIntegral(decimal);
                sysStoreIntegralService.insertCommodityIntegral(intReq, (byte) 0);
            }
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(tdCommodityUserOrder.getStoreId());
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail("未找到门店");
        }
        //判断门店活动
        List<MtActivityOrderResp> actList = mtActivityAppService.orderAndActivity(tdCommodityUserOrder.getStoreId());
        if (CollUtil.isNotEmpty(actList)) {
            for (MtActivityOrderResp orderResp : actList) {
                //判断再活动时间内
                Date date = new Date();
                if (date.after(orderResp.getStartTime()) && date.before(orderResp.getEndTime())) {
                    MtUserJoinActivityProcess process = new MtUserJoinActivityProcess();
                    process.setActId(orderResp.getId());
                    process.setActName(orderResp.getName());
                    process.setActStart(orderResp.getStartTime());
                    process.setActEnd(orderResp.getEndTime());
                    process.setUserAccountId(tdCommodityUserOrder.getStoreId());
                    process.setUserLoginName(storeInfo.getStoreBoss());
                    process.setUserPhone(storeInfo.getConnectWay());
                    process.setDicCode(orderResp.getField());
                    process.setCreatedAt(new Date());
                    process.setUserArea(storeInfo.getAreaId());
                    process.setUserImage(storeInfo.getStoreImage());
                    if (StoreActivityEnum.HJ001.getDicCode().equals(orderResp.getField())) {
                        process.setBizId(td1.getId());
                        mtActivityAppService.insertProcess(process);

                    } else if (StoreActivityEnum.HJ004.getDicCode().equals(orderResp.getField())) {
                        if (CollUtil.isNotEmpty(commodityList)) {
                            boolean flag = isLottery(orderResp.getId());
                            f1:
                            for (TdCommodityOrderDetails orderDetails : commodityList) {
                                if (flag) {
                                    MtActivityRuleBusiness business = mtActivityAppService.selectBusinessByActIdAndComId(orderResp.getId(), String.valueOf(orderDetails.getCommodityId()));
                                    if (ObjectUtil.isEmpty(business)) {
                                        continue f1;
                                    }
                                }
                                for (Integer i = 0; i < orderDetails.getCommodityNum(); i++) {
                                    process.setBizId(orderDetails.getCommodityId());
                                    mtActivityAppService.insertProcess(process);
                                }
                            }
                        }
                    }
                }
            }
            for (MtActivityOrderResp orderResp : actList) {
//                if(isDivide(orderResp.getId())){
                //排名活动不修改达标状态
                MtActivityRule mtActivityRule = mtActivityAppService.selectRuleByMoldAndActId(orderResp.getId(), StoreActivityEnum.PB000.getDicType());
                if (!ObjectUtils.isEmpty(mtActivityRule)) {
                    continue;
                }
                int count = mtActivityAppService.processCount(orderResp.getId(), storeInfo.getId());
                Map<String, Object> map = new HashMap<>();
                map.put("count", count);
                boolean flag = IKExpressionUtil.executeIs("count" + orderResp.getExpression(), map);
                if (flag) {
                    mtActivityAppService.updateUserJoin(orderResp.getId(), storeInfo.getId(), (short) 1);
                }
//                }
            }
        }

        //上门服务订单
        if (td1.getOrderType() == 0) {
            //5.发送门店推送消息
            massageTask.storePushOrder(td1.getStoreId(), EnumMsgType.TODOOR_SERVICE.getName(), EnumMsgType.TODOOR_SERVICE.getValue(), orderNo);
        }

        return ResponseData.success();
    }

    private void updateStoreInfo(String orderNo, Long storeId) {
        List<TdCommodityOrderDetails> tdDetail = tdCommodityUserOrderService.findCommodityByOrderNo(orderNo, (byte) 0);
        if (null != tdDetail && tdDetail.size() > 0) {
            for (TdCommodityOrderDetails td2 : tdDetail) {
                if (!StringUtils.isEmpty(td2.getCommodityBarCode())) {
                    MallCommoditySpecs mallCommoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(td2.getCommodityId(), td2.getCommodityBarCode());
                    if (null != mallCommoditySpecs) {
                        sysStoreStorkService.outStork(storeId, mallCommoditySpecs.getId(), td2.getCommodityId(), td2.getCommodityNum().longValue());
                    } else {
                        sysStoreStorkService.outStork(storeId, null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                    }
                } else {
                    sysStoreStorkService.outStork(storeId, null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                }
            }
        }
    }

    private boolean isLottery(Long actId) {
        return ObjectUtil.isNotEmpty(mtActivityAppService.selectRuleByFieldAndActId(actId, StoreActivityEnum.CJ002.getDicCode()));
    }

}
